package com.cskaoyan.config.shiro;

import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * 自定义会话管理
 * 登录成功，获得sessionId,并返回前端
 * 前端发请求时把sessionId一起发过来（通过请求头）
 * 通过SessionManager获得请求头里的SessionId-->拿到对应的session
 * X-CskaoyanMarket-Admin-Token: 62e863c9-a6f8-4fa8-87eb-f4cb4a658b2e
 * @author yemingfei
 * @since 2022/06/07 15:50
 */
@Component
public class AdminSessionManager extends DefaultWebSessionManager {

    private static final String HEADER = "X-CskaoyanMarket-Admin-Token";
    private static final String WX_HEADER = "X-CskaoyanMarket-Token";

    // 根据请求头获得sessionId
    @Override
    protected Serializable getSessionId(ServletRequest srequest, ServletResponse sresponse) {
        HttpServletRequest request = (HttpServletRequest) srequest;
        String sessionId = request.getHeader(HEADER);
        if (sessionId != null && !"".equals(sessionId)){
            return sessionId;
        }

        String sessionId2 = request.getHeader(WX_HEADER);
        if (sessionId2 != null && !"".equals(sessionId2)){
            return sessionId2;
        }

        return super.getSessionId(srequest, sresponse);
    }
}
